{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LAT Gamma-Ray Burst Analysis\n",
    "\n",
    "This procedure provides a step-by-step example of extracting and modeling a LAT Gamma-Ray Burst observation and modeling the prompt and temporally extended emissions using the X-Ray Spectral Fitting Package (**Xspec**) and **gtlike**, respectively. It should be noted that the LAT Low Energy (LLE) data products can also be used for LAT-detected GRBs (see [GRB Analysis Using GTBurst](https://fermidev.gsfc.nasa.gov/ssc/data/analysis/scitools/gtburst.html))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "* [gtbin](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtbin.txt)\n",
    "* [gtdiffrsp](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtdiffrsp.txt)\n",
    "* [gtexpmap](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtexpmap.txt)\n",
    "* [gtfindsrc](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtfindsrc.txt)\n",
    "* [gtltcube](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtltcube.txt)\n",
    "* [gtmktime](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtmktime.txt)\n",
    "* [gtrspgen](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtrspgen.txt)\n",
    "* [gtselect](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtselect.txt)\n",
    "* [gtvcut](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtvcut.txt)\n",
    "* XSPEC, used as a spectral analysis tool in Step 3 of this procedure (See [Xanadu Data Analysis for X-Ray Astronomy](http://heasarc.gsfc.nasa.gov/docs/xanadu/).)\n",
    "* The FITS viewer [*fv*](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/heasarc.gsfc.nasa.gov/ftools/fv.html)\n",
    "* The astronomical imaging and data visualization application [*ds9*](http://hea-www.harvard.edu/RD/ds9/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Assumptions\n",
    "\n",
    "It is assumed that:\n",
    "\n",
    "* The referenced files reside in your working directory.\n",
    "* You know the time and location of the burst you wish to analyze.\n",
    "\n",
    "    Note: For this thread, we will analyze GRB080916C, one of the brightest LAT GRBs on record. The relevant burst properties are:\n",
    "   \n",
    "     * T0 = 00:12:45.614 UT, 16 September 2008, corresponding to 243216766.614 seconds (MET)\n",
    "     * Trigger # 243216766\n",
    "     * RA = 121.8 degrees\n",
    "     * Dec = -61.3 degrees\n",
    "     \n",
    "* You have extracted the files used in this tutorial. You can download them in the code cell below, or you can extract them yourself in the [LAT Data Server](http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi) with the following selections:\n",
    "```\n",
    "GRB080916C\n",
    "Search Center (RA,Dec) = (121.8,-61.3)\n",
    "Radius = 40 degrees\n",
    "Start Time (MET) = 243216266.6 seconds (2011-03-28T00:00:00)\n",
    "Stop Time (MET) = 243218766.6 seconds (2011-04-04T00:00:00)\n",
    "Minimum Energy = 100 MeV\n",
    "Maximum Energy = 300000 MeV\n",
    "```\n",
    "    In this case, the GRB in question is of a sufficiently short duration, e.g. ~10's of seconds, so that the accumulation of LAT background counts is negligible. In order to study delayed emission, e.g. 10's of minutes to ~hour timescales, a likelihood analysis will be required."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2019-07-09 17:04:50--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/latGrbAnalysis/LAT_GRB_analysis.tgz\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 7543252 (7.2M) [application/x-tar]\n",
      "Saving to: ‘LAT_GRB_analysis.tgz’\n",
      "\n",
      "LAT_GRB_analysis.tg 100%[===================>]   7.19M  30.0MB/s    in 0.2s    \n",
      "\n",
      "2019-07-09 17:04:50 (30.0 MB/s) - ‘LAT_GRB_analysis.tgz’ saved [7543252/7543252]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/latGrbAnalysis/LAT_GRB_analysis.tgz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x ./._LAT_GRB_analysis\n",
      "x LAT_GRB_analysis/\n",
      "x LAT_GRB_analysis/._080916C_LAT.pha\n",
      "x LAT_GRB_analysis/080916C_LAT.pha\n",
      "x LAT_GRB_analysis/._080916C_LAT.rsp\n",
      "x LAT_GRB_analysis/080916C_LAT.rsp\n",
      "x LAT_GRB_analysis/._cmap_zmax100.fits\n",
      "x LAT_GRB_analysis/cmap_zmax100.fits\n",
      "x LAT_GRB_analysis/._extended_expmap.fits\n",
      "x LAT_GRB_analysis/extended_expmap.fits\n",
      "x LAT_GRB_analysis/._extended_ltcube.fits\n",
      "x LAT_GRB_analysis/extended_ltcube.fits\n",
      "x LAT_GRB_analysis/._extended_mktime.fits\n",
      "x LAT_GRB_analysis/extended_mktime.fits\n",
      "x LAT_GRB_analysis/._extended_select.fits\n",
      "x LAT_GRB_analysis/extended_select.fits\n",
      "x LAT_GRB_analysis/._filtered_zmax100.fits\n",
      "x LAT_GRB_analysis/filtered_zmax100.fits\n",
      "x LAT_GRB_analysis/._FT2.fits\n",
      "x LAT_GRB_analysis/FT2.fits\n",
      "x LAT_GRB_analysis/._glg_cspec_n0_bn080916009_v07.rsp\n",
      "x LAT_GRB_analysis/glg_cspec_n0_bn080916009_v07.rsp\n",
      "x LAT_GRB_analysis/._glg_tte_n0_bn080916009_v01.fit\n",
      "x LAT_GRB_analysis/glg_tte_n0_bn080916009_v01.fit\n",
      "x LAT_GRB_analysis/._GRB080916C_model.xml\n",
      "x LAT_GRB_analysis/GRB080916C_model.xml\n",
      "x LAT_GRB_analysis/._L1506171634094365357F22_EV00.fits\n",
      "x LAT_GRB_analysis/L1506171634094365357F22_EV00.fits\n",
      "x LAT_GRB_analysis/._L1506171634094365357F22_SC00.fits\n",
      "x LAT_GRB_analysis/L1506171634094365357F22_SC00.fits\n",
      "x LAT_GRB_analysis/._lc_zmax100.fits\n",
      "x LAT_GRB_analysis/lc_zmax100.fits\n",
      "x LAT_GRB_analysis/._localize_zmax100.fits\n",
      "x LAT_GRB_analysis/localize_zmax100.fits\n",
      "x LAT_GRB_analysis/._prompt_expmap.fits\n",
      "x LAT_GRB_analysis/prompt_expmap.fits\n",
      "x LAT_GRB_analysis/._prompt_select.fits\n",
      "x LAT_GRB_analysis/prompt_select.fits\n",
      "x LAT_GRB_analysis/._results.dat\n",
      "x LAT_GRB_analysis/results.dat\n"
     ]
    }
   ],
   "source": [
    "!mkdir data\n",
    "!mv LAT_GRB_analysis.tgz ./data\n",
    "!tar -xzvf ./data/LAT_GRB_analysis.tgz -C ./data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Steps:\n",
    "\n",
    "1. [Localize the GRB.](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/lat_grb_analysis.html#TS)\n",
    "2. [Generating the analysis files.](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/lat_grb_analysis.html#FILESGEN)\n",
    "3. [Binned analysis with XSPEC (prompt emission).](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/lat_grb_analysis.html#XSPEC)\n",
    "4. [Unbinned analysis using gtlike (extended emission).](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/lat_grb_analysis.html#GTLIKE)\n",
    "\n",
    "**NOTE**: During the analysis of the prompt emission (Steps 1 to 3) we will make use of the `P8R3_TRANSIENT020_V2` [response function](http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_LAT_IRFs/IRF_overview.html), while in the analysis of the extended emission (Step 4) the `P8R3_SOURCE_V2` response function will be used."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. Localize the GRB\n",
    "\n",
    "**a) Select LAT data during prompt burst phase**\n",
    "\n",
    "This can either be done using a time interval ascertained from data from other instruments (e.g., using the GBM trigger time and T90 values reported in the [Fermi/GBM circular](http://gcn.gsfc.nasa.gov/gcn3/8245.gcn3)), or it can be estimated directly from the LAT light curve. Open the light curve `lc_zmax100.fits` with [*fv*](http://heasarc.nasa.gov/ftools/fv/):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/bin/sh: fv: command not found\r\n"
     ]
    }
   ],
   "source": [
    "!fv ./data/LAT_GRB_analysis/lc_zmax100.fits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should get something that looks like this:\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT1_fvzmax100LCerrors.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, we have plotted TIME-243216766 on the x-axis (with TIMEDEL as error) and COUNTS on the y-axis (with ERROR as error). Hovering the cursor over the plot will yield its x-y coordinates; in this case, a plausible estimate of the LAT emission interval is (T0, T0+40s).\n",
    "\n",
    "We run **gtselect** to extract the data for this time interval.\n",
    "\n",
    "Remember to set `evclass=16` on the command line to ensure that we retain the transient class events:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input FT1 file[./data/LAT_GRB_analysis/FT1.fits]     ./data/LAT_GRB_analysis/fil \r",
      "tered_zmax100.fits\n",
      "Output FT1 file[./data/LAT_GRB_analysis/extended_select.fits]     ./data/LAT_GRB \r",
      "_analysis/localize_zmax100.fits\n",
      "RA for new search center (degrees) (0:360) [119.861]     INDEF\n",
      "Dec for new search center (degrees) (-90:90) [-56.581]     INDEF\n",
      "radius of new search region (degrees) (0:180) [15]     15\n",
      "start time (MET in s) (0:) [243216806]     243216766\n",
      "end time (MET in s) (0:) [243217166]     243216806\n",
      "lower energy limit (MeV) (0:) [100]     100\n",
      "upper energy limit (MeV) (0:) [300000]     300000\n",
      "maximum zenith angle value (degrees) (0:180) [100]     100\n",
      "Done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtselect evclass=16\n",
    "    ./data/LAT_GRB_analysis/filtered_zmax100.fits\n",
    "    ./data/LAT_GRB_analysis/localize_zmax100.fits\n",
    "    INDEF\n",
    "    INDEF\n",
    "    15\n",
    "    243216766\n",
    "    243216806\n",
    "    100\n",
    "    300000\n",
    "    100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that we have also reduced the acceptance cone to 15 degrees to filter out non-burst photons."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**b) Run the localization tools, gtfindsrc and gtbin**\n",
    "\n",
    "If the data are essentially background-free as is the case here with a burst duration of ~50 sec, one can run the localization tools **gtfindsrc** and **gtbin** directly on the FT1 file (obtained when downloading the data file from the FSSC LAT Data server).\n",
    "\n",
    "**gtfindsrc** is necessary to centroid the GRB. For longer intervals where the background is significant, we can model the instrumental and celestial backgrounds using diffuse model components. For these data, the integration time is about 40 seconds so the diffuse and instrumental background components will make a negligible contribution to the total counts, so we proceed assuming they are negligible.\n",
    "\n",
    "We run **gtfindsrc** first to find the local maximum of the log-likelihood of a point source model as well as an estimate of the error radius. We will use this information to specify the size of the TS map in order to ensure that it contains the error circles we desire."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event file[]     ./data/LAT_GRB_analysis/localize_zmax100.fits\n",
      "Spacecraft file[]     ./data/LAT_GRB_analysis/L1506171634094365357F22_SC00.fits\n",
      "Output file for trial points[]     ./data/LAT_GRB_analysis/GRB080916C_gtfindsrc. \r",
      "txt\n",
      "Response functions to use[CALDB]     P8R3_TRANSIENT020_V2\n",
      "Livetime cube file[none]     none\n",
      "Unbinned exposure map[none]     none\n",
      "Source model file[none]     none\n",
      "Target source name[]      \n",
      "Source '     ' not found in source model.\n",
      "Enter coordinates for test source:\n",
      "Coordinate system (CEL|GAL) [CEL]     CEL\n",
      "Intial source Right Ascension (deg) (-360:360) [0]     121.8\n",
      "Initial source Declination (deg) (-90:90) [0]     -61.3\n",
      "Optimizer (DRMNFB|NEWMINUIT|MINUIT|DRMNGB|LBFGS) [MINUIT]     MINUIT\n",
      "Tolerance for -log(Likelihood) at each trial point[1e-2]     1e-2\n",
      "Covergence tolerance for positional fit[0.01]     0.01\n",
      "Best fit position: 119.889,  -56.6719\n",
      "Error circle radius: 0.0663046\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtfindsrc\n",
    "    ./data/LAT_GRB_analysis/localize_zmax100.fits\n",
    "    ./data/LAT_GRB_analysis/L1506171634094365357F22_SC00.fits\n",
    "    ./data/LAT_GRB_analysis/GRB080916C_gtfindsrc.txt\n",
    "    P8R3_TRANSIENT020_V2\n",
    "    none\n",
    "    none\n",
    "    none\n",
    "     \n",
    "    CEL\n",
    "    121.8\n",
    "    -61.3\n",
    "    MINUIT\n",
    "    1e-2\n",
    "    0.01"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example of running **gtfindsrc**, the `FT2.fits` file was the renamed spacecraft data file downloaded from the FSSC LAT Data server.\n",
    "\n",
    "Since our source model comprises only a point source to represent the signal from the GRB, we do not provide a source model file or a target source name.\n",
    "\n",
    "Similarly, since the exposure map is used for diffuse components, we do not need to provide an unbinned exposure map. Use of a livetime cube will make the point source exposure calculation faster, but for integrations less than 1000 s, it is generally not needed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have now obtained a position of maximum likelihood; we will use (119.861, -56.581) as our burst location from now on. It should be noted that GRB080916C is an exceptionally bright event in the LAT, and centroiding it with **gtfindsrc** is fast and adequate. In many other cases, a GRB may have far fewer LAT counts and the creation of a counts map using **gtbin** will be useful in localizing it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is gtbin version HEAD\n",
      "Type of output file (CCUBE|CMAP|LC|PHA1|PHA2|HEALPIX) [PHA1]     CMAP\n",
      "Event data file name[./data/LAT_GRB_analysis/prompt_select.fits]     ./data/LAT_ \r",
      "GRB_analysis/localize_zmax100.fits\n",
      "Output file name[./data/LAT_GRB_analysis/080916C_LAT.pha]     ./data/LAT_GRB_ana \r",
      "lysis/GRB080916C_counts_map.fits\n",
      "Spacecraft data file name[./data/LAT_GRB_analysis/FT2.fits]     NONE\n",
      "Size of the X axis in pixels[30]     30\n",
      "Size of the Y axis in pixels[30]     30\n",
      "Image scale (in degrees/pixel)[0.2]     0.2\n",
      "Coordinate system (CEL - celestial, GAL -galactic) (CEL|GAL) [CEL]     CEL\n",
      "First coordinate of image center in degrees (RA or galactic l)[119.861]     119. \r",
      "861\n",
      "Second coordinate of image center in degrees (DEC or galactic b)[-56.581]     -5 \r",
      "6.581\n",
      "Rotation angle of image axis, in degrees[0]     0\n",
      "Projection method e.g. AIT|ARC|CAR|GLS|MER|NCP|SIN|STG|TAN:[AIT]     AIT\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "gtbin: WARNING: No spacecraft file: EXPOSURE keyword will be set equal to ontime.\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtbin\n",
    "    CMAP\n",
    "    ./data/LAT_GRB_analysis/localize_zmax100.fits\n",
    "    ./data/LAT_GRB_analysis/GRB080916C_counts_map.fits\n",
    "    NONE\n",
    "    30\n",
    "    30\n",
    "    0.2\n",
    "    CEL\n",
    "    119.861\n",
    "    -56.581\n",
    "    0\n",
    "    AIT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now view the counts map in *ds9*:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ds9 ./data/LAT_GRB_analysis/GRB080916C_counts_map.fits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The counts map should look something like this:\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT2_ds9countsmap.png'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. Generating the analysis files\n",
    "\n",
    "In this subsection, we'll use the same data we extracted as for the localization analysis above.\n",
    "\n",
    "The purpose is to illustrate the steps necessary to model a GRB that is significantly fainter than GRB080916C; i.e., one for which the residual and diffuse backgrounds need to be modeled. This means that we will include diffuse components in the model definition and that will necessitate the exposure map calculation in order for the code to compute the predicted number of events. We'll see from the fit to the data that these diffuse components do indeed provide a negligible contribution to the overall counts for this burst."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**a) Data subselection**\n",
    "\n",
    "Rerun **gtselect** with (119.861, -56.581) as the new search center:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input FT1 file[./data/LAT_GRB_analysis/filtered_zmax100.fits]     ./data/LAT_GRB \r",
      "_analysis/filtered_zmax100.fits\n",
      "Output FT1 file[./data/LAT_GRB_analysis/localize_zmax100.fits]     ./data/LAT_GR \r",
      "B_analysis/prompt_select.fits\n",
      "RA for new search center (degrees) (0:360) [INDEF]     119.861\n",
      "Dec for new search center (degrees) (-90:90) [INDEF]     -56.581\n",
      "radius of new search region (degrees) (0:180) [15]     15\n",
      "start time (MET in s) (0:) [243216766]     243216766\n",
      "end time (MET in s) (0:) [243216806]     243216806\n",
      "lower energy limit (MeV) (0:) [100]     100\n",
      "upper energy limit (MeV) (0:) [300000]     300000\n",
      "maximum zenith angle value (degrees) (0:180) [100]     100\n",
      "Done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtselect evclass=16\n",
    "    ./data/LAT_GRB_analysis/filtered_zmax100.fits\n",
    "    ./data/LAT_GRB_analysis/prompt_select.fits\n",
    "    119.861\n",
    "    -56.581\n",
    "    15\n",
    "    243216766\n",
    "    243216806\n",
    "    100\n",
    "    300000\n",
    "    100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**b) Model definition**\n",
    "\n",
    "The model will include a point source at the GRB location, an isotropic component (to represent the extragalactic diffuse and/or the residual background), and a Galactic diffuse component that uses the recommend Galactic diffuse model, `gal_2yearp7v6_v0.fits`. This file is available at the [LAT background models](http://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html) page via the [FSSC Data Access](http://fermi.gsfc.nasa.gov/ssc/data/access/) page.\n",
    "\n",
    "The easiest way to generate a simple 3 component model like this would be to use the [modeleditor](http://www.slac.stanford.edu/exp/glast/wb/prod/pages/sciTools_modeleditor/modelEditor.html) program (included in the [Fermitools](http://fermi.gsfc.nasa.gov/ssc/data/analysis/software/)) by typing `ModelEditor` at the prompt."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT3_modEd.png'>\n",
    "\n",
    "Here, we have added three sources to our model:\n",
    "\n",
    "1. GRB_080916C (you can rename the source by typing into the \"Source Name:\" text input box), with a PowerLaw2 spectrum. (The [Model Selection](http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Likelihood/Model_Selection.html) page of the Cicerone lists the possible spectral models.)\n",
    "\n",
    "    We have adjusted the Lower Limit of its spectrum to be 100.0. We have also inputted the RA and Dec (calculated from gtfindsrc) into its spatial model. We have kept all other default values.\n",
    "\n",
    "\n",
    "2. GALPROP Diffuse (there is a specific option for this in the \"Source\" menu). Edit the `File:` entry of the spatial model to point to your local copy of `gll_iem_v06.fits`. We have kept all other defaults.\n",
    "\n",
    "\n",
    "3. Extragalactic Diffuse (there is a specific option for this). We have kept all the default values.\n",
    "\n",
    "If our analysis region had been close to any known LAT sources, we would have had to include them in our model (see this [tutorial](http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html#createSourceModel))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The xml file `GRB080916C_model.xml` should look like this:\n",
    "\n",
    "```xml\n",
    "<?xml version=\"1.0\" ?>\n",
    "<source_library title=\"Source Library\" xmlns=\"http://fermi.gsfc.nasa.gov/source_library\">\n",
    "  <source name=\"GRB_080916C\" type=\"PointSource\">\n",
    "    <spectrum type=\"PowerLaw2\">\n",
    "      <parameter free=\"true\" max=\"1000.0\" min=\"1e-05\" name=\"Integral\" scale=\"1e-06\" value=\"1.0\"/>\n",
    "      <parameter free=\"true\" max=\"-1.0\" min=\"-5.0\" name=\"Index\" scale=\"1.0\" value=\"-2.0\"/>\n",
    "      <parameter free=\"false\" max=\"200000.0\" min=\"20.0\" name=\"LowerLimit\" scale=\"1.0\" value=\"20.0\"/>\n",
    "      <parameter free=\"false\" max=\"200000.0\" min=\"20.0\" name=\"UpperLimit\" scale=\"1.0\" value=\"200000.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel type=\"SkyDirFunction\">\n",
    "      <parameter free=\"false\" max=\"360.0\" min=\"0.0\" name=\"RA\" scale=\"1.0\" value=\"119.861\"/>\n",
    "      <parameter free=\"false\" max=\"90.0\" min=\"-90.0\" name=\"DEC\" scale=\"1.0\" value=\"-56.581\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "  <source name=\"GALPROP Diffuse Source\" type=\"DiffuseSource\">\n",
    "    <spectrum type=\"ConstantValue\">\n",
    "      <parameter free=\"true\" max=\"10.0\" min=\"0.0\" name=\"Value\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel file=\"$(FERMI_DIR)/refdata/fermi/galdiffuse/gll_iem_v06.fits\" type=\"MapCubeFunction\">\n",
    "      <parameter free=\"false\" max=\"1000.0\" min=\"0.001\" name=\"Normalization\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "  <source name=\"Extragalactic Diffuse Source\" type=\"DiffuseSource\">\n",
    "    <spectrum type=\"PowerLaw\">\n",
    "      <parameter free=\"true\" max=\"100.0\" min=\"1e-05\" name=\"Prefactor\" scale=\"1e-07\" value=\"1.6\"/>\n",
    "      <parameter free=\"false\" max=\"-1.0\" min=\"-3.5\" name=\"Index\" scale=\"1.0\" value=\"-2.1\"/>\n",
    "      <parameter free=\"false\" max=\"200.0\" min=\"50.0\" name=\"Scale\" scale=\"1.0\" value=\"100.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel type=\"ConstantValue\">\n",
    "      <parameter free=\"false\" max=\"10.0\" min=\"0.0\" name=\"Value\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "</source_library>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also create and edit model files by hand rather than use the modeleditor so long as the sources have the correct formats."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For your convenience, you can create a local copy of the xml by running the python script below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('./data/LAT_GRB_analysis/GRB080916C_model.xml', 'w') as file:\n",
    "    file.write(\"\"\"<?xml version=\"1.0\" ?>\n",
    "<source_library title=\"Source Library\" xmlns=\"http://fermi.gsfc.nasa.gov/source_library\">\n",
    "  <source name=\"GRB_080916C\" type=\"PointSource\">\n",
    "    <spectrum type=\"PowerLaw2\">\n",
    "      <parameter free=\"true\" max=\"1000.0\" min=\"1e-05\" name=\"Integral\" scale=\"1e-06\" value=\"1.0\"/>\n",
    "      <parameter free=\"true\" max=\"-1.0\" min=\"-5.0\" name=\"Index\" scale=\"1.0\" value=\"-2.0\"/>\n",
    "      <parameter free=\"false\" max=\"200000.0\" min=\"20.0\" name=\"LowerLimit\" scale=\"1.0\" value=\"20.0\"/>\n",
    "      <parameter free=\"false\" max=\"200000.0\" min=\"20.0\" name=\"UpperLimit\" scale=\"1.0\" value=\"200000.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel type=\"SkyDirFunction\">\n",
    "      <parameter free=\"false\" max=\"360.0\" min=\"0.0\" name=\"RA\" scale=\"1.0\" value=\"119.861\"/>\n",
    "      <parameter free=\"false\" max=\"90.0\" min=\"-90.0\" name=\"DEC\" scale=\"1.0\" value=\"-56.581\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "  <source name=\"GALPROP Diffuse Source\" type=\"DiffuseSource\">\n",
    "    <spectrum type=\"ConstantValue\">\n",
    "      <parameter free=\"true\" max=\"10.0\" min=\"0.0\" name=\"Value\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel file=\"$(FERMI_DIR)/refdata/fermi/galdiffuse/gll_iem_v06.fits\" type=\"MapCubeFunction\">\n",
    "      <parameter free=\"false\" max=\"1000.0\" min=\"0.001\" name=\"Normalization\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "  <source name=\"Extragalactic Diffuse Source\" type=\"DiffuseSource\">\n",
    "    <spectrum type=\"PowerLaw\">\n",
    "      <parameter free=\"true\" max=\"100.0\" min=\"1e-05\" name=\"Prefactor\" scale=\"1e-07\" value=\"1.6\"/>\n",
    "      <parameter free=\"false\" max=\"-1.0\" min=\"-3.5\" name=\"Index\" scale=\"1.0\" value=\"-2.1\"/>\n",
    "      <parameter free=\"false\" max=\"200.0\" min=\"50.0\" name=\"Scale\" scale=\"1.0\" value=\"100.0\"/>\n",
    "    </spectrum>\n",
    "    <spatialModel type=\"ConstantValue\">\n",
    "      <parameter free=\"false\" max=\"10.0\" min=\"0.0\" name=\"Value\" scale=\"1.0\" value=\"1.0\"/>\n",
    "    </spatialModel>\n",
    "  </source>\n",
    "</source_library>\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**c) Refining the good time intervals (GTIs)**\n",
    "\n",
    "In general, our next step would be to run **gtmktime** to remove the time intervals whose events fell outside of our zenith angle cut and apply temporal cuts to the data based on the spacecraft file (`FT2.fits`). However, as our data encompasses a short period of time, this step is inappropriate in this case (**gtmktime** will report errors).\n",
    "\n",
    "It would be necessary if were analyzing a longer period of time such as a longer burst, or extended emission as at the end of this thread (see the [Likelihood Tutorial](http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html) for more information).\n",
    "\n",
    "Also, if we use **gtvcut** to review the file `prompt_select.fits`, we can see that the GTIs span the entire time selection we have made."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**d) Diffuse response calculation**\n",
    "\n",
    "Since we are dealing with `evclass=16` (transient class) events, we need to run the **gtdiffrsp** tool.\n",
    "\n",
    "For each diffuse component in the model, the **gtdiffrsp** tool populates the `DIFRSP0` and `DIFRSP1` columns. They contain the integral over the source extent (for the Galactic and isotropic components this is essentially the entire sky) of the source intensity spatial distribution times the PSF and effective area. It computes the counts model density of the various diffuse components at each measured photon location, arrival time, and energy, and this information is used in maximizing the likelihood computation. This integral is also computed for the point sources in the model, but since those sources are delta-functions in sky position, the spatial part of the integral is trivial.\n",
    "\n",
    "Note that the large size of the [new Galactic diffuse background model](http://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html) makes this a very resource-intensive process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2019-07-09 17:05:04--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/software/aux/gll_iem_v06.fits\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 498021120 (475M) [application/fits]\n",
      "Saving to: ‘gll_iem_v06.fits’\n",
      "\n",
      "gll_iem_v06.fits    100%[===================>] 474.95M  47.0MB/s    in 12s     \n",
      "\n",
      "2019-07-09 17:05:16 (39.1 MB/s) - ‘gll_iem_v06.fits’ saved [498021120/498021120]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/software/aux/gll_iem_v06.fits\n",
    "!mv gll_iem_v06.fits $FERMI_DIR/refdata/fermi/galdiffuse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event data file[./data/LAT_GRB_analysis/extended_mktime.fits]     ./data/LAT_GRB \r",
      "_analysis/prompt_select.fits\n",
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Source model file[./data/LAT_GRB_analysis/GRB080916C_model.xml]     ./data/LAT_G \r",
      "RB_analysis/GRB080916C_model.xml\n",
      "Response functions to use[P8R3_SOURCE_V2]     P8R3_TRANSIENT020_V2\n",
      "adding source Extragalactic Diffuse Source\n",
      "adding source GALPROP Diffuse Source\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "Working on...\n",
      "./data/LAT_GRB_analysis/prompt_select.fits....................!\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtdiffrsp\n",
    "    ./data/LAT_GRB_analysis/prompt_select.fits\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/GRB080916C_model.xml\n",
    "    P8R3_TRANSIENT020_V2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As mentioned before, **gtdiffrsp** modifies the input file by adding values to the `DIFRSP0` and `DIFRSP1` columns. In the tar file, for comparison purposes, the user can find two copies of the input file, one used as input of **gtdiffrsp** (named `prompt_select_pre_gtdiffrsp.fits`) and one obtained after running with **gtdiffrsp** and with the columns modified (named `prompt_select.fits`)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**e) Livetime cube generation**\n",
    "\n",
    "For analysis of longer time intervals, we would need to run **gtltcube** to calculate a livetime cube. For this analysis, this step is unnecessary due to the short timescales involved."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**f) Exposure map generation**\n",
    "\n",
    "We now use **gtexpmap** to generate the [exposure map](http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data_Exploration/livetime_and_exposure.html). Note that the exposure maps from this tool are intended for use with **unbinned likelihood analysis only**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event data file[./data/LAT_GRB_analysis/extended_mktime.fits]     ./data/LAT_GRB \r",
      "_analysis/prompt_select.fits\n",
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Exposure hypercube file[./data/LAT_GRB_analysis/extended_ltcube.fits]     none\n",
      "output file name[./data/LAT_GRB_analysis/extended_expmap.fits]     ./data/LAT_GR \r",
      "B_analysis/prompt_expmap.fits\n",
      "Response functions[P8R3_SOURCE_V2]     P8R3_TRANSIENT020_V2\n",
      "Radius of the source region (in degrees)[25]     25\n",
      "Number of longitude points (2:1000) [100]     100\n",
      "Number of latitude points (2:1000) [100]     100\n",
      "Number of energies (2:100) [20]     20\n",
      "Computing the ExposureMap (no expCube file given) \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "The exposure maps generated by this tool are meant\n",
      "to be used for *unbinned* likelihood analysis only.\n",
      "Do not use them for binned analyses.\n",
      "....................!\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtexpmap\n",
    "    ./data/LAT_GRB_analysis/prompt_select.fits\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    none\n",
    "    ./data/LAT_GRB_analysis/prompt_expmap.fits\n",
    "    P8R3_TRANSIENT020_V2\n",
    "    25\n",
    "    100\n",
    "    100\n",
    "    20"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The radius of the source region should be larger than the extraction region in the FT1 data in order to account for PSF tail contributions of sources just outside the extraction region.\n",
    "\n",
    "For energies down to 100 MeV, a 10 degree buffer is recommended (i.e., the total radius is the sum of the extraction radius and the buffer area, totaling 25 in our case); for higher energy lower bounds, e.g., 1 GeV, 5 degrees or less is acceptable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, note that we did not provide an \"exposure hypercube\" (the livetime cube) file.\n",
    "\n",
    "For data durations less than about 1ks, **gtexpmap** will execute faster doing the time integration over the livetimes in the FT2 file directly. For longer integrations, computing the livetime cube with **gtltcube** will be faster (more information can be found in the [Explore LAT Data section](http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/explore_latdata.html)). At this step, the flux and spectral shape of the GRB prompt emission can be estimated using the **gtlike** tool (see section 4f)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3. Binned analysis with XSPEC (prompt emission)\n",
    "\n",
    "We will now perform a spectral analysis on the prompt emission using XSPEC. (A basic knowledge of the use of XSPEC is assumed.)\n",
    "\n",
    "This requires a `PHA` (spectral) file and a `RSP` (response) file. It should be noted that as an alternative to XSPEC, the RMFIT software (available as a user contribution) can be used for spectral modeling; however, it is not distributed as part of the Fermitools."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**a) Generating PHA and RSP files**\n",
    "\n",
    "We use **gtbin** to create the `PHA1` file (the choice of `PHA1` for `Type of output file` indicates that you want to create a `PHA` file — the standard FITS file containing a single binned spectrum — spanning the entire time range):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is gtbin version HEAD\n",
      "Type of output file (CCUBE|CMAP|LC|PHA1|PHA2|HEALPIX) [CMAP]     PHA1\n",
      "Event data file name[./data/LAT_GRB_analysis/localize_zmax100.fits]     ./data/L \r",
      "AT_GRB_analysis/prompt_select.fits\n",
      "Output file name[./data/LAT_GRB_analysis/GRB080916C_counts_map.fits]     ./data/ \r",
      "LAT_GRB_analysis/080916C_LAT.pha\n",
      "Spacecraft data file name[NONE]     ./data/LAT_GRB_analysis/FT2.fits\n",
      "Algorithm for defining energy bins (FILE|LIN|LOG) [LOG]     LOG\n",
      "Start value for first energy bin in MeV[100]     100\n",
      "Stop value for last energy bin in MeV[300000]     300000\n",
      "Number of logarithmically uniform energy bins[30]     30\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtbin\n",
    "    PHA1\n",
    "    ./data/LAT_GRB_analysis/prompt_select.fits\n",
    "    ./data/LAT_GRB_analysis/080916C_LAT.pha\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    LOG\n",
    "    100\n",
    "    300000\n",
    "    30"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The **gtrspgen** tool is then run to generate an XSPEC-compatible response matrix from the LAT IRFs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is gtrspgen version HEAD\n",
      "Response calculation method (GRB|PS) [GRB]     PS\n",
      "Spectrum file name[]     ./data/LAT_GRB_analysis/080916C_LAT.pha\n",
      "Spacecraft data file name[]     ./data/LAT_GRB_analysis/FT2.fits\n",
      "Output file name[]     ./data/LAT_GRB_analysis/080916C_LAT.rsp\n",
      "Cutoff angle for binning SC pointings (degrees)[60.]     90\n",
      "Size of bins for binning SC pointings (cos(theta))[.05]     0.5\n",
      "Response function to use, Handoff|DC2|DC2A|DC2FA|DC2BA|DC2FB etc[P6_V3_DIFFUSE]  \r",
      "    CALDB\n",
      "Algorithm for defining true energy bins (FILE|LIN|LOG) [LOG]     LOG\n",
      "Start value for first energy bin in MeV[30.]     100\n",
      "Stop value for last energy bin in MeV[200000.]     300000\n",
      "Number of logarithmically uniform energy bins[100]     100\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtrspgen\n",
    "    PS\n",
    "    ./data/LAT_GRB_analysis/080916C_LAT.pha\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/080916C_LAT.rsp\n",
    "    90\n",
    "    0.5\n",
    "    CALDB\n",
    "    LOG\n",
    "    100\n",
    "    300000\n",
    "    100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Notes**:\n",
    "\n",
    "* One should always use the `PS` response calculation method despite the option of using `GRB`. The latter was a method used in the early stages of the software creation but was later never fully developed. Ultimately, the `PS` method should always be more accurate, in particular for longer bursts. For short bursts, the difference in results and execution time between `PS` and `GRB` is negligible.\n",
    "\n",
    "\n",
    "* In **gtrspgen** you choose the incident photon energy bins; i.e., the energy bins over which the incident photon model is computed. **gtrspgen** reads the output photon channel energy grid from the PHA file. The RSP created by **gtrspgen** is the mapping from the incident photon energy bins into the output photon channels. These incident photon energy bins need not be the same as the output channels and they should generally over-sample them:\n",
    "    * If there are only a few channels then the calculation of the expected number of photons in each channel will be more accurate if there are more incident photon energy bins.\n",
    "    * You might want to include some incident photon energy bins above and below the range of channels to account for the LAT's finite energy resolution. Incident energy bins above the highest channel energy is particularly important if some for the photon's energy leaks out of the detector."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**b) Backgrounds**\n",
    "\n",
    "For the prompt emission of GRB 080916C (and most LAT bursts), there is minimal background contamination. For analyses of longer integrations, one can estimate the background using off-source regions as for more traditional X-ray analyses."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**c) Running XSPEC**\n",
    "\n",
    "You now have the two files necessary to analyze the burst spectrum with XSPEC:\n",
    "\n",
    "* A PHA file with the spectrum.\n",
    "* A RSP file with the response function.\n",
    "\n",
    "Note that there is no background file. All non-burst sources are expected to produce less than 1 photon in the extraction region during the burst! Here we provide the simplest example of fitting a spectrum with XSPEC; for further details you should consult the [XSPEC manual](http://heasarc.gsfc.nasa.gov/docs/xanadu/xspec/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. Start XSPEC\n",
    "\n",
    "**Note**: The default version is now release 12 (XSPEC12)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. Load in the data:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```%%bash\n",
    ">>xspec\n",
    "data ./data/080916C_LAT.pha```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you specify a data file, XSPEC will try to load the response file in the PHA file's header. Alternatively, you can specify the response file separately with the command `response 080916C_LAT.rsp`.\n",
    "\n",
    "We now load in a power law model for fitting the data. For more information on available models, see [this example](http://heasarc.gsfc.nasa.gov/docs/xanadu/xspec/xspec11/manual/node26.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. Load the model:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```%%bash\n",
    ">>xspec\n",
    "model pow```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. Set XSPEC to plot the data and to select the statistical method for fitting:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    ">>xspec\n",
    "cpd /xs\n",
    "setplot energy\n",
    "plot ldata chi\n",
    "statistic cstat```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `cpd` command sets the current plotting device, which in this case is the `xserve` option (an xwindow that persists after XSPEC has been closed).\n",
    "\n",
    "The next two commands tell XSPEC to create a logarithmic (the \"l\" of `ldata`) plot of the energy (along the x-axis), using the data file specified before, with the fit statistic. (Consult the [manual](http://heasarc.gsfc.nasa.gov/docs/xanadu/xspec/xspec11/manual/node26.html) for another example.)\n",
    "\n",
    "It is important to note that, for LAT GRB analysis, we generally want to use the C-statistic instead of chi-squared due to the small number of counts. (However, the command for plotting is still `chi` or `chisq` regardless of the statistic used.) We have set this in the last step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5. Perform a fit and plot the results:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```%%bash\n",
    ">>xspec\n",
    "fit\n",
    "plot ldata resid\n",
    "plot ldata ratio```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "They should all be invoked in the same xspec instance, so combining all of the steps above will yield:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "bash: line 2: xspec: command not found\n",
      "bash: line 3: data: command not found\n",
      "bash: line 4: model: command not found\n",
      "bash: line 7: cpd: command not found\n",
      "bash: line 8: setplot: command not found\n",
      "bash: line 9: plot: command not found\n",
      "bash: line 10: statistic: command not found\n",
      "bash: line 11: fit: command not found\n",
      "bash: line 12: plot: command not found\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "#For ldata resid\n",
    "xspec\n",
    "data ./data/LAT_GRB_analysis/080916C_LAT.pha\n",
    "model pow\n",
    "\n",
    "\n",
    "cpd /xs\n",
    "setplot energy\n",
    "plot ldata chi\n",
    "statistic cstat\n",
    "fit\n",
    "plot ldata resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This will give you something that looks like: <img src=\"https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT4_xspec_ldata_res.png\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "bash: line 2: xspec: command not found\n",
      "bash: line 3: data: command not found\n",
      "bash: line 4: model: command not found\n",
      "bash: line 7: cpd: command not found\n",
      "bash: line 8: setplot: command not found\n",
      "bash: line 9: plot: command not found\n",
      "bash: line 10: statistic: command not found\n",
      "bash: line 11: fit: command not found\n",
      "bash: line 12: plot: command not found\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "# For ldata ratio\n",
    "xspec\n",
    "data ./data/LAT_GRB_analysis/080916C_LAT.pha\n",
    "model pow\n",
    "\n",
    "\n",
    "cpd /xs\n",
    "setplot energy\n",
    "plot ldata chi\n",
    "statistic cstat\n",
    "fit\n",
    "plot ldata ratio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And this will give you something that looks like: <img src=\"https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT5_xspec_ldata_ratio.png\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. Unbinned analysis using gtlike (temporally expanded emission)\n",
    "\n",
    "**a) Data subselection**\n",
    "\n",
    "Here, we will search for emission which may occur after the prompt GRB event; temporally extended high-energy emission has been detected in a large number of LAT bursts. \n",
    "\n",
    "We rerun **gtselect** on a time interval of ~40 to 400 seconds after the trigger on the file downloaded from the archive (i.e. the EV file) and renamed `FT1.fits`, choosing to [exclude \"transient\"](http://fermi.gsfc.nasa.gov/ssc/data/analysis/LAT_caveats.html) class photons for the analysis of extended emission. (A longer interval has been chosen to demonstrate **gtmktime**, **gtltcube**, etc.)\n",
    "\n",
    "Remember to set `evclass=128` on the command line to ensure that we use the source class events."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make a copy of the EV file and rename it to FT1.fits.\n",
    "!cp ./data/LAT_GRB_analysis/L1506171634094365357F22_EV00.fits ./data/LAT_GRB_analysis/FT1.fits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input FT1 file[./data/LAT_GRB_analysis/filtered_zmax100.fits]     ./data/LAT_GRB \r",
      "_analysis/FT1.fits\n",
      "Output FT1 file[./data/LAT_GRB_analysis/prompt_select.fits]     ./data/LAT_GRB_a \r",
      "nalysis/extended_select.fits\n",
      "RA for new search center (degrees) (0:360) [119.861]     119.861\n",
      "Dec for new search center (degrees) (-90:90) [-56.581]     -56.581\n",
      "radius of new search region (degrees) (0:180) [15]     15\n",
      "start time (MET in s) (0:) [243216766]     243216806\n",
      "end time (MET in s) (0:) [243216806]     243217166\n",
      "lower energy limit (MeV) (0:) [100]     100\n",
      "upper energy limit (MeV) (0:) [300000]     300000\n",
      "maximum zenith angle value (degrees) (0:180) [100]     100\n",
      "Done.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtselect evclass=128\n",
    "    ./data/LAT_GRB_analysis/FT1.fits\n",
    "    ./data/LAT_GRB_analysis/extended_select.fits\n",
    "    119.861\n",
    "    -56.581\n",
    "    15\n",
    "    243216806\n",
    "    243217166\n",
    "    100\n",
    "    300000\n",
    "    100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**b) Refining the GTIs**\n",
    "\n",
    "Since our subselection encompasses a longer period of time, we run gtmktime to exclude bad time intervals with the filter expression suggested in the [Cicerone](https://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Filter expression[(DATA_QUAL>0)&&(LAT_CONFIG==1)]     (DATA_QUAL>0)&&(LAT_CONFIG \r",
      "==1)\n",
      "Apply ROI-based zenith angle cut[yes]     yes\n",
      "Event data file[./data/LAT_GRB_analysis/extended_select.fits]     ./data/LAT_GRB \r",
      "_analysis/extended_select.fits\n",
      "Output event file name[./data/LAT_GRB_analysis/extended_mktime.fits]     ./data/ \r",
      "LAT_GRB_analysis/extended_mktime.fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtmktime\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    (DATA_QUAL>0)&&(LAT_CONFIG==1)\n",
    "    yes\n",
    "    ./data/LAT_GRB_analysis/extended_select.fits\n",
    "    ./data/LAT_GRB_analysis/extended_mktime.fits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: In an analysis of *transient* class events, we set the data quality portion of the filter expression to `DATA_QUAL>0` to retain these events."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**c) Diffuse response calculation**\n",
    "\n",
    "We run now **gtdiffrsp**, making sure to use the correct response function.\n",
    "\n",
    "Again, note that the pass 8 Galactic diffuse background model causes this to be very resource-intensive. The tool modifies the input event data file, inserting values in the `DIFRSP0` and `DIFRSP1` columns.\n",
    "\n",
    "<!--- (A copy of the input file (named `extended_mktime_pre_gtdiffrsp.fits`), generated before running **gtdiffrsp**, can be found in the [tar file](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/latGrbAnalysis/LAT_GRB_analysis.tgz).) --->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event data file[./data/LAT_GRB_analysis/prompt_select.fits]     ./data/LAT_GRB_a \r",
      "nalysis/extended_mktime.fits\n",
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Source model file[./data/LAT_GRB_analysis/GRB080916C_model.xml]     ./data/LAT_G \r",
      "RB_analysis/GRB080916C_model.xml\n",
      "Response functions to use[P8R3_TRANSIENT020_V2]     P8R3_SOURCE_V2\n",
      "adding source Extragalactic Diffuse Source\n",
      "adding source GALPROP Diffuse Source\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "Working on...\n",
      "./data/LAT_GRB_analysis/extended_mktime.fits.........................!\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtdiffrsp\n",
    "    ./data/LAT_GRB_analysis/extended_mktime.fits\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/GRB080916C_model.xml\n",
    "    P8R3_SOURCE_V2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**d) Livetime cube generation**\n",
    "\n",
    "Now that our data file encompasses a longer period of time, it requires us to calculate the livetime cube using **gtltcube**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event data file[./data/LAT_GRB_analysis/extended_mktime.fits]     ./data/LAT_GRB \r",
      "_analysis/extended_mktime.fits\n",
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Output file[./data/LAT_GRB_analysis/extended_ltcube.fits]     ./data/LAT_GRB_ana \r",
      "lysis/extended_ltcube.fits\n",
      "Step size in cos(theta) (0.:1.) [0.025]     0.025\n",
      "Pixel size (degrees)[0.5]     0.5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "Working on file ./data/LAT_GRB_analysis/FT2.fits\n",
      "..............!\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtltcube\n",
    "    ./data/LAT_GRB_analysis/extended_mktime.fits\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/extended_ltcube.fits\n",
    "    0.025\n",
    "    0.5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**e) Exposure map generation**\n",
    "\n",
    "This time we will specify a livetime cube file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Event data file[./data/LAT_GRB_analysis/prompt_select.fits]     ./data/LAT_GRB_a \r",
      "nalysis/extended_mktime.fits\n",
      "Spacecraft data file[./data/LAT_GRB_analysis/FT2.fits]     ./data/LAT_GRB_analys \r",
      "is/FT2.fits\n",
      "Exposure hypercube file[none]     ./data/LAT_GRB_analysis/extended_ltcube.fits\n",
      "output file name[./data/LAT_GRB_analysis/prompt_expmap.fits]     ./data/LAT_GRB_ \r",
      "analysis/extended_expmap.fits\n",
      "Response functions[P8R3_TRANSIENT020_V2]     P8R3_SOURCE_V2\n",
      "Radius of the source region (in degrees)[25]     25\n",
      "Number of longitude points (2:1000) [100]     100\n",
      "Number of latitude points (2:1000) [100]     100\n",
      "Number of energies (2:100) [20]     20\n",
      "Computing the ExposureMap using ./data/LAT_GRB_analysis/extended_ltcube.fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "The exposure maps generated by this tool are meant\n",
      "to be used for *unbinned* likelihood analysis only.\n",
      "Do not use them for binned analyses.\n",
      "....................!\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtexpmap\n",
    "    ./data/LAT_GRB_analysis/extended_mktime.fits\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/extended_ltcube.fits\n",
    "    ./data/LAT_GRB_analysis/extended_expmap.fits\n",
    "    P8R3_SOURCE_V2\n",
    "    25\n",
    "    100\n",
    "    100\n",
    "    20"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**f) Calculating the likelihood**\n",
    "\n",
    "We will use **gtlike** for this analysis. The `plot=yes` command brings up a plot of the fit results; `results=results.dat` saves a copy of the fit results to the file `results.dat`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Statistic to use (BINNED|UNBINNED) [UNBINNED]     UNBINNED\n",
      "Spacecraft file[none]     ./data/LAT_GRB_analysis/FT2.fits\n",
      "Event file[none]     ./data/LAT_GRB_analysis/extended_mktime.fits\n",
      "Unbinned exposure map[none]     ./data/LAT_GRB_analysis/extended_expmap.fits\n",
      "Exposure hypercube file[none]     ./data/LAT_GRB_analysis/extended_ltcube.fits\n",
      "Source model file[]     ./data/LAT_GRB_analysis/GRB080916C_model.xml\n",
      "Response functions to use[CALDB]     P8R3_SOURCE_V2\n",
      "Optimizer (DRMNFB|NEWMINUIT|MINUIT|DRMNGB|LBFGS) [MINUIT]     MINUIT\n",
      " **********\n",
      " **    1 **SET PRINT     .000    \n",
      " **********\n",
      " **********\n",
      " **    2 **SET NOWARN \n",
      " **********\n",
      "\n",
      " PARAMETER DEFINITIONS:\n",
      "    NO.   NAME         VALUE      STEP SIZE      LIMITS\n",
      "     1 'Prefactor '    1.6000       1.0000         .10000E-04   100.00    \n",
      "     2 'Value     '    1.0000       1.0000          .0000       10.000    \n",
      "     3 'Integral  '    1.0000       1.0000         .10000E-04   1000.0    \n",
      "     4 'Index     '   -2.0000       1.0000        -5.0000      -1.0000    \n",
      " **********\n",
      " **    3 **SET ERR    .5000    \n",
      " **********\n",
      " **********\n",
      " **    4 **SET GRAD    1.000    \n",
      " **********\n",
      " **********\n",
      " **    5 **MINIMIZE    800.0       2.000    \n",
      " **********\n",
      "\n",
      " MIGRAD MINIMIZATION HAS CONVERGED.\n",
      "\n",
      " MIGRAD WILL VERIFY CONVERGENCE AND ERROR MATRIX.\n",
      "\n",
      " FCN=   612.1321     FROM MIGRAD    STATUS=CONVERGED     70 CALLS       71 TOTAL\n",
      "                     EDM=   .80E-04    STRATEGY= 1      ERROR MATRIX ACCURATE \n",
      "\n",
      "  EXT PARAMETER                                   STEP         FIRST   \n",
      "  NO.   NAME        VALUE          ERROR          SIZE      DERIVATIVE \n",
      "   1  Prefactor     .21271E-04    .99149        .84415E-01** at limit **\n",
      "   2  Value         2.1292        .42566        .46267E-01    .37155E-01\n",
      "   3  Integral      321.48        90.971        .43760E-01    .81086E-01\n",
      "   4  Index        -2.0185        .12374        .16695E-01    .15893    \n",
      "                               ERR DEF=  .500    \n",
      "Final values: \n",
      "  Prefactor  = 2.12712e-05\n",
      "  Value      = 2.12921\n",
      "  Integral   = 321.485\n",
      "  Index      = -2.01851\n",
      " **********\n",
      " **    6 **HESSE \n",
      " **********\n",
      "\n",
      " FCN=   612.1321     FROM HESSE     STATUS=OK            23 CALLS       94 TOTAL\n",
      "                     EDM=   .73E-04    STRATEGY= 1      ERROR MATRIX ACCURATE \n",
      "\n",
      "  EXT PARAMETER                                INTERNAL      INTERNAL  \n",
      "  NO.   NAME        VALUE          ERROR       STEP SIZE       VALUE   \n",
      "   1  Prefactor     .21271E-04    1.0063        .24006E-02   -1.5715    \n",
      "                                 WARNING -   - ABOVE PARAMETER IS AT LIMIT.\n",
      "   2  Value         2.1292        .42399        .24968E-03    5.6716    \n",
      "   3  Integral      321.48        79.580        .20312E-03   -.36509    \n",
      "   4  Index        -2.0185        .10807        .73783E-04    19.363    \n",
      "                               ERR DEF=  .500    \n",
      "Minuit fit quality: 3   estimated distance: 7.2751e-05\n",
      "Minuit parameter uncertainties:\n",
      "  1  0.00674714\n",
      "  2  0.42475\n",
      "  3  79.9698\n",
      "  4  0.108139\n",
      "Computing TS values for each source (3 total)\n",
      "\n",
      "Photon fluxes are computed for the energy range 100 to 300000 MeV\n",
      "\n",
      "Extragalactic Diffuse Source:\n",
      "Prefactor: 2.12712e-05 +/- 0.00674714\n",
      "Index: -2.1\n",
      "Scale: 100\n",
      "Npred: 4.35898e-05\n",
      "Flux: 2.43125e-09 +/- 7.70682e-07 photons/cm^2/s\n",
      "\n",
      "GALPROP Diffuse Source:\n",
      "Value: 2.12921 +/- 0.42475\n",
      "Npred: 28.6587\n",
      "Flux: 0.0010404 +/- 0.00020753 photons/cm^2/s\n",
      "\n",
      "GRB_080916C:\n",
      "Integral: 321.485 +/- 79.9698\n",
      "Index: -2.01851 +/- 0.108139\n",
      "LowerLimit: 20\n",
      "UpperLimit: 200000\n",
      "Npred: 70.4164\n",
      "ROI distance: 0\n",
      "TS value: 451.168\n",
      "Flux: 6.24327e-05 +/- 8.09301e-06 photons/cm^2/s\n",
      "\n",
      "\n",
      "Total number of observed counts: 99\n",
      "Total number of model events: 99.0752\n",
      "\n",
      "-log(Likelihood): 612.1321133\n",
      "\n",
      "Elapsed CPU time: 22.44168\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "...!\n",
      "WARNING: Fit may be bad in range [740.083, 1104.43] (MeV)\n",
      "WARNING: Fit may be bad in range [1648.13, 3670.33] (MeV)\n",
      "/Users/echau1/miniconda2/envs/fermi/lib/python2.7/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n",
      "  warnings.warn(message, mplDeprecation, stacklevel=1)\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "gtlike plot=yes results=./data/LAT_GRB_analysis/results.dat\n",
    "    UNBINNED\n",
    "    ./data/LAT_GRB_analysis/FT2.fits\n",
    "    ./data/LAT_GRB_analysis/extended_mktime.fits\n",
    "    ./data/LAT_GRB_analysis/extended_expmap.fits\n",
    "    ./data/LAT_GRB_analysis/extended_ltcube.fits\n",
    "    ./data/LAT_GRB_analysis/GRB080916C_model.xml\n",
    "    P8R3_SOURCE_V2\n",
    "    MINUIT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The plot produced by **gtlike** shows the fitting results: The red, green, and blue lines correspond to the fit of the extragalactic diffuse background, the galactic diffuse background, and the GRB, respectively (as explained in the [Run gtlike](http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html#runLikelihood) section of the [Likelihood Tutorial](http://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html)). The black line is the sum of the 3 components.\n",
    "\n",
    "In our model, we included the galactic and extragalactic diffuse backgrounds. In a real analysis, we would have also included any known sources within ~20 or so degrees of the burst.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/latGrbAnalysis/LAT6_gtlike.png'>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
